package com.maple.handler;

import com.maple.enumeration.ExceptionEnum;
import com.maple.exception.BusinessException;
import com.maple.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 全局异常处理器
  */
@RestControllerAdvice
@Slf4j
public class ExceptionGlobalHandler {

    // 接收业务的异常
    @ExceptionHandler(BusinessException.class)
    public Result exceptionHandler(BusinessException e){
        log.error("业务异常处理器开始运行，错误信息：{}",e.getMsg());

        return Result.error(e);
    }

    // TODO 之后要解开
    // 兜底异常处理器，接收所有未意料的异常
//    @ExceptionHandler(Throwable.class)
//    public Result exceptionHandler(Throwable t){
//        log.error("兜底异常处理器开始运行");
//
//        return Result.error(404,"服务器错误，未知异常");
//    }

    // TODO 要修改返回值信息
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public Result exceptionHandler(SQLIntegrityConstraintViolationException e){
        log.error("SQL错误信息：{}",e.getMessage());

        return Result.error(ExceptionEnum.ALREADY_EXISTS);
    }

}
